import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import { useDispatch } from 'react-redux';
import { DrawerForm } from '@ant-design/pro-components';
import { useDebounce } from '@cfe/hooks';
import { Form, Input, message, Radio, Select } from 'antd';

import { requestWithoutCache } from '@/utils/request';

const { useForm } = Form;
const createFilter = (crowdList = [], logic) => {
  return {
    type: logic,
    filters: crowdList.map((id) => ({ type: 'crowd', crowd_id: +id })),
  };
};

const CombineCrowdContent = forwardRef((_, ref) => {
  const [crowdOptions, setCrowdOptions] = useState();
  const [coverage, setCoverage] = useState(null);
  const [form] = useForm();

  const handleValueChange = useDebounce((field) => {
    if (!field[0].name.includes('crowd') && !field[0].name.includes('logic'))
      return;
    const value = form.getFieldsValue();
    const { crowd, logic } = value;
    if (!crowd || crowd.length === 0 || !logic) return;
    const filter = createFilter(crowd, logic);
    requestWithoutCache('/api/dmp/crowd/coverage', {
      method: 'POST',
      body: JSON.stringify(filter),
    }).then((res) => {
      setCoverage(res.data.coverage);
    });
  }, 300);

  useImperativeHandle(ref, () => {
    return { form, crowdOptions, setCoverage };
  });

  useEffect(() => {
    requestWithoutCache('/api/dmp/crowd/all').then((res) => {
      setCrowdOptions(
        res.data?.map(({ name, id }) => ({ label: name, value: id })),
      );
    });
  }, []);

  return (
    <Form form={form} onFieldsChange={handleValueChange}>
      <Form.Item
        name="crowd"
        label="选择人群:"
        rules={[{ min: 2, message: '请至少选择两个人群', type: 'array' }]}
      >
        <Select
          options={crowdOptions}
          style={{ marginLeft: '16px' }}
          mode="multiple"
          showSearch
          filterOption={(input, option) => {
            return option.label.includes(input);
          }}
        />
      </Form.Item>
      <Form.Item
        label="组合方式:"
        initialValue="and"
        rules={[{ required: true }]}
        name="logic"
      >
        <Radio.Group
          style={{ marginLeft: '16px' }}
          options={[
            { label: '人群交集', value: 'and' },
            { label: '人群并集', value: 'or' },
            { label: '人群差集', value: 'not' },
          ]}
        />
      </Form.Item>
      <Form.Item label="覆盖数量">
        <span style={{ marginLeft: '16px' }}>
          {coverage ? `${coverage} 人` : '0'}
        </span>
      </Form.Item>
      <Form.Item label="人群名称" name="name">
        <Input style={{ marginLeft: '16px' }} placeholder="请输入人群名称" />
      </Form.Item>
    </Form>
  );
});

const CombineCrowdModal = ({ visible, onVisibleChange }) => {
  const contentRef = useRef(null);
  const dispatch = useDispatch();
  // eslint-disable-next-line no-unused-vars
  const selectGroupTag = (payload) => {
    dispatch({ type: 'label/selectGroupTag', payload });
  };

  const handleFinish = () => {
    contentRef.current.form.validateFields().then(() => {
      const { crowd, logic, name } = contentRef.current.form.getFieldsValue();
      const filter = createFilter(crowd, logic);

      const body = {
        product_type: 1, //todo: 这可能是不合理的，但是又怎么拿呢？
        limit: 0,
        refresh_interval: 0, //todo: 这个呢？
        crowd_type: 2,
        name,
        filter,
      };
      requestWithoutCache('/api/dmp/crowd/create', {
        method: 'POST',
        body: JSON.stringify(body),
      }).then((res) => {
        if (res.status === 0) {
          // selectGroupTag({
          //   groupTagData,
          //   value: Object.values(value),
          //   groupId,
          //   dimId: dimId ?? propsGroupTagInfo.dimId,
          //   groupTagInfo: groupTagInfo ?? propsGroupTagInfo,
          //   crowdId: crowd_id,
          // })
          message.success('创建成功');
          onVisibleChange(false);
          contentRef.current.setCoverage(null);
          contentRef.current.form.resetFields();
        }
      });
    });
  };

  return (
    <DrawerForm
      title="人群组合"
      width={500}
      open={visible}
      onVisibleChange={onVisibleChange}
      onFinish={handleFinish}
      onClose={onVisibleChange}
      drawerProps={{
        destroyOnClose: true,
      }}
    >
      <CombineCrowdContent ref={contentRef} />
    </DrawerForm>
  );
};

export default CombineCrowdModal;
